package com.imooc.sell.utils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static final String FILEPATH = "C:\\Users\\tuhan\\IdeaProjects\\tuhanSE\\src\\com\\tuhan";
    public static final String importPackage = "import com.tuhan.parent.TestParent;";
    public static  final String extendsParent = " extends TestParent";

    public static void main(String[] args) throws Exception {
        //给文件添加定义的引用包 和 继承类
        function(FILEPATH);
    }

    public  static void function(String path) throws Exception {

       // List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
             String fileName = tempList[i].getName();
             String javamodel = fileName.substring(0,fileName.lastIndexOf("."));
                tianjia(FILEPATH +"\\"+fileName);
                autoReplace(tempList[i].toString(),javamodel,javamodel + extendsParent);
            }
        }
        System.out.println("success");
    }
    private static void tianjia(String path) throws Exception {
        // 使用一个字符串集合来存储文本中的路径 ，也可用String []数组
        //List<String> list = new ArrayList<String>();
        FileInputStream fis = new FileInputStream(path);
        // 防止路径乱码   如果utf-8 乱码  改GBK     eclipse里创建的txt  用UTF-8，在电脑上自己创建的txt  用GBK
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line = "";
        while ((line = br.readLine()) != null) {
            if(line.contains(";")){
                String newLine = line + importPackage;
                autoReplace(path,line,newLine);
                break;
            }
        }
        br.close();
        isr.close();
        fis.close();
        //while((line=bReader.readLine())!=null){ //按行读取数据
    }
    private static void autoReplace(String filePath, String oldstr, String newStr) {
        File file = new File(filePath);
        Long fileLength = file.length();
        byte[] fileContext = new byte[fileLength.intValue()];
        FileInputStream in = null;
        PrintWriter out = null;
        try {
            in = new FileInputStream(filePath);
            in.read(fileContext);
            // 避免出现中文乱码
            String str = new String(fileContext, "utf-8");
            str = str.replace(oldstr, newStr);
            out = new PrintWriter(filePath);
            out.write(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
